package com.caregiver.watch.business.care.service.strategy.impl;

import com.alibaba.fastjson2.JSON;
import com.caregiver.watch.business.care.dao.HealthAlertConfigDao;
import com.caregiver.watch.business.care.enums.HealthAlertTypeEnum;
import com.caregiver.watch.business.care.model.bo.AlertMessageBo;
import com.caregiver.watch.business.care.model.bo.BloodPressureWarningConfig;
import com.caregiver.watch.business.care.model.po.HealthAlertConfig;
import com.caregiver.watch.business.care.service.UserAlertRecordService;
import com.caregiver.watch.business.care.service.strategy.AbstractHealthWarningStrategy;
import com.caregiver.watch.business.data.protobuf.AlarmInfo;
import com.caregiver.watch.business.data.utils.time.DateTimeUtils;
import com.caregiver.watch.business.user.model.po.UserCareRecipient;
import com.caregiver.watch.business.user.service.UserDeviceService;
import com.caregiver.watch.common.utils.time.DateUtils;
import com.caregiver.watch.thirdparty.service.JPushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.caregiver.watch.common.constant.NumberConstants.ZERO;

/**
 * @Description: 血压预警策略
 * @Author 疆戟
 * @Date 2025/11/2 17:39
 * @Version 1.0
 */
@Component
@Slf4j
public class BloodPressureWarningStrategy extends AbstractHealthWarningStrategy<List<AlarmInfo.BpConf>> {

    public BloodPressureWarningStrategy(UserDeviceService userDeviceService, HealthAlertConfigDao healthAlertConfigDao, UserAlertRecordService userAlertRecordService, JPushService jPushService) {
        super(userDeviceService, healthAlertConfigDao, userAlertRecordService, jPushService);
    }

    @Override
    public void handle(Long userId, String deviceUuId, List<AlarmInfo.BpConf> bpAlarmList) {
        log.info("处理血压预警：{}", bpAlarmList);
        HealthAlertConfig config = getConfig();
        if (Objects.isNull(config)) {
            log.warn("未查询到血压预警配置");
            return;
        }
        if (BooleanUtils.isNotTrue(config.getEnabled())) {
            log.warn("未启用血压预警");
            return;
        }
        String alertConfig = config.getAlertConfig();
        log.info("血压预警配置：{}", alertConfig);
        if (StringUtils.isBlank(alertConfig)) {
            log.warn("未配置血压预警");
            return;
        }
        // 获取被关照人
        UserCareRecipient userCareRecipient = queryContactDeviceDetail(userId, deviceUuId);
        if (Objects.isNull(userCareRecipient)) {
            log.warn("未查询到被关照人");
            return;
        }
        List<BloodPressureWarningConfig> bloodPressureWarningConfigs = JSON.parseArray(alertConfig, BloodPressureWarningConfig.class);
        if (CollectionUtils.isEmpty(bloodPressureWarningConfigs)) {
            log.warn("未配置血压预警");
            return;
        }
        AlarmInfo.BpConf bpAlarm = bpAlarmList.get(ZERO);
        // 获取告警时间
        LocalDateTime alarmTime = DateUtils.convert2LocalDateTime(bpAlarm.getTimeStamp().getDateTime().getSeconds());
        log.info("bp alarm time:{},收缩压:{},舒张压:{}", alarmTime, bpAlarm.getSbp(), bpAlarm.getDbp());
        // 舒张压
        int dbp = bpAlarm.getDbp();
        // 收缩压
        int sbp = bpAlarm.getSbp();
        Optional<BloodPressureWarningConfig> first = bloodPressureWarningConfigs.stream().filter(warningConfig -> {
            // 如果没有最大值 就比最小值打就行
            if (Objects.isNull(warningConfig.getMaxSystolic()) || Objects.isNull(warningConfig.getMaxDiastolic())) {
                return warningConfig.getMinSystolic() <= sbp && warningConfig.getMinDiastolic() <= dbp;
            }
            return warningConfig.getMaxSystolic() >= sbp && warningConfig.getMinSystolic() <= sbp
                    && warningConfig.getMaxDiastolic() >= dbp && warningConfig.getMinDiastolic() <= dbp;
        }).findFirst();
        if (!first.isPresent()) {
            log.warn("未匹配到血压预警配置");
            return;
        }
        BloodPressureWarningConfig warningConfig = first.get();
        log.info("匹配到血压预警配置：{}", warningConfig);
        AlertMessageBo alertMessage = AlertMessageBo.build(warningConfig.getWarningTitle(), String.valueOf(sbp), warningConfig.getThreshold(), warningConfig.getHandleSuggestions());
        // 发送告警
        Boolean sendPush = sendPush(userId, userCareRecipient.getRecipientId(), config.getAlertType(), alarmTime, alertMessage);
        if (BooleanUtils.isTrue(sendPush)) {
            // 记录告警
            saveAlertRecord(userId, userCareRecipient.getRecipientId(), config.getAlertType(), alarmTime, JSON.toJSONString(alertMessage));
        }
    }

    @Override
    public HealthAlertTypeEnum getAlertType() {
        return HealthAlertTypeEnum.BP_WARNING;
    }
}
